﻿using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace WT.OpenIddict.Domain.Shared;

public static class EnumExtension
{
    public static string GetDisplayName(this Enum eum)
    {
        var type = eum.GetType(); //先获取这个枚举的类型
        var field = type.GetField(eum.ToString()); //通过这个类型获取到值
        var obj = (DisplayAttribute)field.GetCustomAttribute(typeof(DisplayAttribute)); //得到特性
        return obj.Name ?? "";
    }

    public static TEnum GetEnumValueFromNumber<TEnum>(int number) where TEnum : Enum
    {
        if (Enum.IsDefined(typeof(TEnum), number)) return (TEnum)Enum.ToObject(typeof(TEnum), number);
        throw new ArgumentException($"The value {number} is not defined in the enum {typeof(TEnum).Name}");
    }
}